import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter_elm/json/cart_item.dart';
import 'package:flutter_elm/json/response_item.dart';
import 'package:flutter_elm/json/user_item.dart';

//code 2开头都是请求成功的，只不过业务上可能不成功
//code 4开头都是请求不成功的。（一般都是 客户端-前端代码问题）
class CartApi {
  late Dio _dio;
  String baseUrl = "http://192.168.1.12:8080/CartController";
  String contents = "";
  var response = null;

  CartApi() {
    _dio = Dio();
    // 设置contentType
    // _dio.options.headers['Content-Type'] = 'application/x-www-form-unlencoded';
  }

  Future<ResponseItem<List<CartItem>?>> findCartsByUidAndBid(String uid, String bid) async {
    var url =  baseUrl+"/findAllByUidOrByUidAndBid";
    //发送formdata 或者 x-www-form-urlencoded 格式的数据 需要用FormData封装
    FormData formData = FormData.fromMap({"uid": uid, "bid": bid});
    try {
      response = await _dio.post(
          url,
          data: formData
      );
//如果没有该type类型，或者该类型没有商家，就会返回[]
//       print(response.data);
      if(response.data.length==0){
        return ResponseItem(code: 201, data: null, message: "该用户$uid在该商家$bid没有添加商品进购物车");
      }else{
        List rd = response.data;
        List<CartItem> cartItemList = rd.map((e) => CartItem.fromJson(e)).toList();
        // print("response.data[0]['food']['foodId']：${response.data[0]['food']['foodId']}");
        // print("cartItemList[0].food.foodName：${cartItemList[0].food.foodName}");
        return ResponseItem<List<CartItem>>(code: 200, data: cartItemList, message: "查找成功");
      }
    } catch (e) {
      if(response.data.length==0){
        print('******getBusinessByType-Error: $e');
        return ResponseItem(code: 400, data: null, message: "客户端代码有问题，$e");
      }else{
        print('******getBusinessByType-Error: $e');
        List rd = response.data;
        List<CartItem> cartItemList = rd.map((e) => CartItem.fromJson(e)).toList();
        return ResponseItem<List<CartItem>>(code: 202, data: cartItemList, message: "查找成功，但是系统发现错误：$e");
      }
    }
  }

}

void main()async{
  CartApi cartApi = CartApi();
  // var res = await cartApi.userRegister("11111178912", "12345678912", "小李", 1);
  var res = await cartApi.findCartsByUidAndBid("12345678912", "10002");
  print("${res.code}:${res.message}");
}